package com.markbuikema.juliana32.fragment;

import java.util.Observable;
import java.util.Observer;

import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TextView;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import com.markbuikema.juliana32.R;
import com.markbuikema.juliana32.enums.CompType;
import com.markbuikema.juliana32.enums.GameType;
import com.markbuikema.juliana32.model.teams.GameEvent;
import com.markbuikema.juliana32.model.teams.Table;
import com.markbuikema.juliana32.model.teams.TableRow;
import com.markbuikema.juliana32.model.teams.Team;
import com.markbuikema.juliana32.util.Constants;
import com.markbuikema.juliana32.util.DataManager;
import com.markbuikema.juliana32.util.Util;

public class TeamFragment extends Fragment implements Observer {

	private Team team;

	private TextView teamNameBig;
	private ImageView teamPhoto;
	private LinearLayout teamContentContainer;
	private ScrollView view;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		int teamIndex = getArguments().getInt("team_index");
		team = DataManager.getInstance().getTeams().get(teamIndex);
		
		team.addObserver(this);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		view = (ScrollView) inflater.inflate(R.layout.fragment_team, container, false);

		teamNameBig = (TextView) view.findViewById(R.id.team_name_big);
		teamContentContainer = (LinearLayout) view.findViewById(R.id.team_content_container);
		teamPhoto = (ImageView) view.findViewById(R.id.team_photo);
		
		teamNameBig.setTypeface(Util.getRobotoThin(getActivity()));

		teamNameBig.setText(team.getName());

		updateInfo();
		updateTeamPhoto();
		return view;
	}
	
	private void updateTeamPhoto() {
		UrlImageViewHelper.setUrlDrawable(teamPhoto, team.getTeamPhoto(), R.drawable.team_placeholder);
	}

	private void updateInfo() {
		teamContentContainer.removeAllViews();

		LayoutInflater inflater = LayoutInflater.from(teamContentContainer.getContext());

		for (CompType type : team.getLeagues().keySet()) {
			String typeStr = "";
			String titleTypeStr = "";
			switch (type) {
			case CUP:
				typeStr = "beker";
				titleTypeStr += "beker";
				break;
			case PLAYOFF:
				typeStr = "nacompetitie ";
				titleTypeStr += "nacompetitie";
				break;
			case REGULAR:
				titleTypeStr += "competitie";
				break;
			case FRIENDLY:
				titleTypeStr += "oefenwedstrijden";
				break;
			}

			final String typeString = typeStr;
			final String titleTypeString = titleTypeStr;

			putGameInfo(GameType.PAST, type, inflater, typeString, titleTypeString);
			putGameInfo(GameType.UPCOMING, type, inflater, typeString, titleTypeString);

			ViewPager tablePager = new ViewPager(getActivity());
			LayoutParams pagerParams = new LayoutParams(LayoutParams.MATCH_PARENT, 600);
			tablePager.setLayoutParams(pagerParams);

			for (Table table : team.getLeagues().get(type).getTables()) {
				if (CompType.get(table.getCompType()) != type)
					continue;

				View view = inflater.inflate(R.layout.view_table, null);

				TextView title = (TextView) view.findViewById(R.id.team_table_title);
				title.setTypeface(Util.getRobotoThin(getActivity()));
				title.setText(table.getName());

				TableLayout layout = (TableLayout) view.findViewById(R.id.team_ranking_table);

				for (TableRow row : table.getRows()) {
					ViewGroup rowView = (ViewGroup) inflater.inflate(R.layout.list_table_row, null);

					ImageView img = (ImageView) rowView.findViewById(R.id.table_row_image);
					TextView position = (TextView) rowView.findViewById(R.id.table_row_position);
					TextView teamName = (TextView) rowView.findViewById(R.id.table_row_name);
					TextView played = (TextView) rowView.findViewById(R.id.table_row_played);
					TextView points = (TextView) rowView.findViewById(R.id.table_row_points);

					position.setTypeface(Util.getRobotoSlabLight(getActivity()));
					teamName.setTypeface(Util.getRobotoLight(getActivity()));
					played.setTypeface(Util.getRobotoLight(getActivity()));
					points.setTypeface(Util.getRobotoLight(getActivity()));

					UrlImageViewHelper.setUrlDrawable(img, row.getImgUrl());
					position.setText(Integer.toString(row.getPosition()));
					teamName.setText(row.getTeamName());
					played.setText(Integer.toString(row.getPlayed()));
					points.setText(Integer.toString(row.getPoints()));

					layout.addView(rowView);
				}

//				tablePager.addView(view);
				teamContentContainer.addView(view);
			}

//			teamContentContainer.addView(tablePager);
		}
	}

	private void putGameInfo(final GameType gameTime, CompType type, LayoutInflater inflater, final String typeString, final String titleTypeString) {
		if (team.getLeagues().get(type).getGames(gameTime) != null && team.getLeagues().get(type).getGames(gameTime).size() > 0) {

			final View upcomingGames = inflater.inflate(R.layout.view_games, null);
			final ViewGroup upcomingGamesContainer = (ViewGroup) upcomingGames.findViewById(R.id.team_games_container);
			final Button upcomingGamesExpandButton = (Button) upcomingGames.findViewById(R.id.team_games_more);
			final TextView upcomingGamesTitle = (TextView) upcomingGames.findViewById(R.id.team_games_title);
			final View upcomingGamesExpandButtonDivider = upcomingGames.findViewById(R.id.team_games_button_divider);

			upcomingGamesExpandButton.setTypeface(Util.getRobotoCondensed(getActivity()));
			upcomingGamesExpandButton.setVisibility(team.getLeagues().get(type).getGames(gameTime).size() > 1 ? View.VISIBLE : View.GONE);
			upcomingGamesExpandButton.setText(gameTime == GameType.PAST ? R.string.show_past_games : R.string.show_upcoming_games);
			upcomingGamesExpandButtonDivider.setVisibility(team.getLeagues().get(type).getGames(gameTime).size() > 1 ? View.VISIBLE : View.GONE);

			upcomingGamesTitle.setText(String.format(getResources().getString(gameTime == GameType.PAST ? R.string.last_game:R.string.next_game), typeString));
			
			upcomingGamesExpandButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (getResources().getString(gameTime == GameType.PAST ? R.string.show_past_games : R.string.show_upcoming_games).equals(upcomingGamesExpandButton.getText())) {
						for (int i = 0; i < upcomingGamesContainer.getChildCount(); i++) {

							View view = upcomingGamesContainer.getChildAt(i);
							view.setVisibility(View.VISIBLE);
							String newTitle = String.format(getResources().getString(gameTime == GameType.PAST ? R.string.past_games : R.string.upcoming_games), titleTypeString);
							upcomingGamesTitle.setText(newTitle);
							upcomingGamesExpandButton.setText(R.string.hide);

						}
					} else {
						for (int i = 1; i < upcomingGamesContainer.getChildCount(); i++) {

							View view = upcomingGamesContainer.getChildAt(i);
							view.setVisibility(View.GONE);
							upcomingGamesTitle.setText(String.format(getResources().getString(gameTime == GameType.PAST ? R.string.last_game:R.string.next_game), typeString));
							upcomingGamesExpandButton.setText(gameTime == GameType.PAST ? R.string.show_past_games : R.string.show_upcoming_games);

							
						}
						
						int y = upcomingGames.getTop() + teamPhoto.getHeight();
						view.setScrollY(y);
					}
				}
			});

			upcomingGamesTitle.setTypeface(Util.getRobotoThin(getActivity()));
			upcomingGamesTitle.setText(String.format(getResources().getString(gameTime == GameType.PAST ? R.string.last_game:R.string.next_game), typeString));

			for (int g = 0; g < team.getLeagues().get(type).getGames(gameTime).size(); g++) {

				GameEvent game = team.getLeagues().get(type).getGames(gameTime).get(g);

				View view = inflater.inflate(R.layout.list_team_game, null);

				ImageView homeLogo = (ImageView) view.findViewById(R.id.agenda_game_home_logo);
				ImageView awayLogo = (ImageView) view.findViewById(R.id.agenda_game_away_logo);
				TextView homeTeam = (TextView) view.findViewById(R.id.agenda_game_home_team);
				TextView awayTeam = (TextView) view.findViewById(R.id.agenda_game_away_team);
				TextView homeGoals = (TextView) view.findViewById(R.id.agenda_game_home_goals);
				TextView awayGoals = (TextView) view.findViewById(R.id.agenda_game_away_goals);
				TextView referee = (TextView) view.findViewById(R.id.agenda_game_referee);
				TextView date = (TextView) view.findViewById(R.id.agenda_game_date);
				TextView location = (TextView) view.findViewById(R.id.agenda_game_location);
				TextView warning = (TextView) view.findViewById(R.id.agenda_game_warning);

				homeGoals.setTypeface(Util.getRobotoSlabLight(getActivity()));
				awayGoals.setTypeface(Util.getRobotoSlabLight(getActivity()));

				referee.setTypeface(Util.getRobotoThin(getActivity()));
				date.setTypeface(Util.getRobotoThin(getActivity()));
				location.setTypeface(Util.getRobotoLight(getActivity()));

				homeTeam.setTypeface(Util.getRobotoCondensed(getActivity()), game.getThuisTeam().contains("Juliana") ? Typeface.BOLD : Typeface.NORMAL);
				awayTeam.setTypeface(Util.getRobotoCondensed(getActivity()), game.getUitTeam().contains("Juliana") ? Typeface.BOLD : Typeface.NORMAL);

				UrlImageViewHelper.setUrlDrawable(homeLogo, game.getThuisLogo());
				UrlImageViewHelper.setUrlDrawable(awayLogo, game.getUitLogo());

				homeTeam.setText(game.getThuisTeam());
				awayTeam.setText(game.getUitTeam());
				date.setText(game.getDateString());

				if (game.getThuisGoals().equals("null")) {
					homeGoals.setVisibility(View.GONE);
				} else {
					homeGoals.setText(game.getThuisGoals());
					homeGoals.setVisibility(View.VISIBLE);
				}

				if (game.getUitGoals().equals("null")) {
					awayGoals.setVisibility(View.GONE);
				} else {
					awayGoals.setText(game.getUitGoals());
					awayGoals.setVisibility(View.VISIBLE);
				}

				if (game.getReferee().isEmpty())
					referee.setVisibility(View.GONE);
				else {
					String ref = String.format(getResources().getString(R.string.referee), game.getReferee());
					referee.setVisibility(View.VISIBLE);
					referee.setText(ref);
				}

				if (game.getLocationName().isEmpty()) {
					location.setVisibility(View.GONE);
				} else {
					location.setVisibility(View.VISIBLE);
					location.setText(game.getLocationName() + ", " + game.getLocationCity());
				}

				if (game.getWarning() != null) {
					warning.setVisibility(View.VISIBLE);
					warning.setText(game.getWarning().getReason());
				} else {
					warning.setVisibility(View.GONE);
				}

				view.setVisibility(g > 0 ? View.GONE : View.VISIBLE);

				upcomingGamesContainer.addView(view);
			}

			teamContentContainer.addView(upcomingGames);
		}
	}

	@Override
	public void update(Observable observable, Object data) {

		int changed = (Integer) data;

		switch (changed) {
		case Constants.CHANGED_TEAM_PHOTO:
			Log.d("teamphoto", team.getName() + " updated!");
			updateTeamPhoto();
			break;
		case Constants.CHANGED_GAMES_PAST:
		case Constants.CHANGED_GAMES_UPCOMING:
		case Constants.CHANGED_LEAGUES:
		case Constants.CHANGED_TABLES:
			updateInfo();
			break;
		}

	}
}
